<template>
	<view class="head"
		style="background-color: #ffcc00; height: 180rpx; display: flex; position: fixed; top: 0; left: 0; right: 0; z-index: 999;">
		<view style="height: fit-content; margin-top: 15%; margin-left: 35%; font-size: 32rpx;">客户端-我的</view>
	</view>
	<view class="homepage">
		<view class="people">

			<view class="headImg">
				<button class="avatar-button" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
					<image class="avatar" :src="userInfo.headImg || '../../../static/images/travel/personal/用户.png'">
					</image>
				</button>
			</view>


			<view class="info">
				<view class="nick">
					<text>{{ isLoggedIn ? (userInfo.name ? userInfo.name : '用户未设置姓名') : '未登录' }}</text>
				</view>
				<view class="userId">
					<image src="../../../static/images/travel/personal/电话.png"></image>
					<text>{{ userInfo.phoneNumber || '请登录后查看' }}</text>
				</view>
				<view class="user-details">
					<!-- <text>姓名: {{ userInfo.name || '未登录' }}</text> -->
				</view>
			</view>
			<view v-if="!isLoggedIn" class="login-button" @click="handleLoginClick">
				<text>立即登录</text>
			</view>
		</view>
		<view class="list">
			<view class="item" v-for="(item, index) in listItems" :key="index">
				<view class="text">
					<text>{{ item.count }}</text>
					<text>{{ item.label }}</text>
				</view>
				<u-line direction="col" color="#979797" length="32rpx"></u-line>
			</view>
		</view>
		<view class="infos">
			<view class="tool">
				<text class="orderTitle">我的今日预约</text>
				<view v-if="todayAppointments && todayAppointments.length > 0">
					<view v-for="(appointment, index) in todayAppointments" :key="index" class="nav-item">
						<text class="thing">{{ appointment.serviceName }}</text>
						<text class="time">{{ appointment.startTime }} - {{ appointment.endTime }}</text>
					</view>
				</view>

				<!-- 如果todayAppointments为空，则显示暂无预约记录 -->
				<view v-else class="no-appointment-tip">
					<text>暂无预约记录</text>
				</view>
			</view>
			<view class="order-buttons">
				<button class="order-button" @click="navigateToPage('/pages/customer-platform/order/index?tab=0')">
					<img src="../../../static/images/my/order.png" class="button-icon" />
					<text font-size="8rpx">全部订单</text>
				</button>
				<button class="order-button" @click="navigateToPage('/pages/customer-platform/order/index?tab=1')">
					<img src="../../../static/images/my/待服务.png" class="button-icon" /> 
					<text font-size="8rpx">待服务</text>
				</button>
				<button class="order-button" @click="navigateToPage('/pages/customer-platform/order/index?tab=2')">
					<img src="../../../static/images/my/pendingfinish.png" class="button-icon" /> 
					<text font-size="8rpx">服务中</text>

				</button>
				<button class="order-button" @click="navigateToPage('/pages/customer-platform/order/index?tab=3')">
					
					<img src="../../../static/images/my/pingjia.png" class="button-icon" />
					<text font-size="8rpx">评价中心</text>
				</button>
			</view>


			<view class="set">
				<view v-for="(item, index) in setItems" :key="index" @click="handleFunctionClick(item)">
					<image class="icon" :src="item.icon"></image>
					<text>{{ item.text }}</text>
					<image class="right" src="../../../static/images/travel/personal/Clipped.png"></image>
				</view>
			</view>

			<!-- <view class="service">
		  <view @click="navigateToPage('/pages/customer-platform/admin')">
			<image class="icon" src="../../../static/images/travel/personal/pic02.png"></image>
			<text>系统后台管理</text>
			<image class="right" src="../../../static/images/travel/personal/Clipped.png"></image>
		  </view>
		</view> -->

		</view>
		<view class="change">
			<button class="change_user" @click="switchUserType('client')">切换为客户端</button>
			<button class="change_nurse" @click="switchUserType('nurse')">切换为护工端</button>
		</view>
	</view>

	<view v-if="showAuthModal" class="auth-modal">
		<view class="auth-modal-content">
			<view class="auth-modal-header">
				<text class="auth-modal-title">提示</text>
			</view>
			<view class="auth-modal-body">
				<text class="auth-modal-text">您还未登录，请先授权获取手机号</text>
			</view>
			<view class="auth-modal-footer">
				<button class="auth-modal-button auth-modal-button-cancel" @click="showAuthModal = false">
					取消
				</button>
				<button class="auth-modal-button auth-modal-button-confirm" open-type="getPhoneNumber"
					@getphonenumber="handleGetPhoneNumber">
					授权登录
				</button>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import { wxLogin } from '@/api/wxlogin/wxlogin';
import { getCustomerOrderList } from '@/api/system/login';
import { getOpenId} from '@/api/wxlogin/wxlogin';

// 定义方法
const navigateToPage = (url) => {
	console.log(`Navigating to ${url}`);

	// 检查登录状态
	if (!isLoggedIn.value) {
		uni.showToast({
			title: '请先登录',
			icon: 'none'
		});
		return;
	}

	// 使用 uni.navigateTo 进行页面跳转
	uni.navigateTo({
		url: url,
		success: () => {
			console.log('Successfully navigated to target page');
		},
		fail: (err) => {
			console.error('Navigation failed:', err);
		}
	});
};

const switchUserType = (type) => {
	if (type === 'nurse') {
		// 检查护工端是否已登录
		const isNurseLoggedIn = uni.getStorageSync('nurseisLoggedIn');
		if (!isNurseLoggedIn) {
			// 未登录，跳转到护工端登录页面
			uni.navigateTo({ url: '/pages/login/index' });
		} else {
			// 已登录，跳转到护工端首页
			uni.navigateTo({ url: '/pages/nurse-platform/index/index' });
		}
	} else {
		// 切换回客户端首页
		uni.switchTab({ url: '/pages/customer-platform/index/index' });
	}
};

// 数据定义
const navItems = ref([
	{ thing: '家政保洁', time: '早上8:00' },
	{ thing: '家政保洁', time: '早上11:30' },
	{ thing: '家政保洁', time: '下午15:00' },
	{ thing: '家政保洁', time: '晚上20:00' },
]);

//   const listItems = ref([
// 	{ count: '0', label: '关注' },
// 	{ count: '0', label: '粉丝' },
// 	{ count: '0', label: '动态' },
// 	{ count: '0', label: '访客' },
//   ]);

const setItems = ref([
	{
		icon: '../../../static/images/travel/personal/pic03.png',
		text: '我的所有预约',
		url: '/pages/customer-platform/my/history'
	},
	{
		icon: '../../../static/images/travel/personal/pic02.png',
		text: '修改个人资料',
		url: '/pages/customer-platform/my/changeInfo'
	},
	{
		icon: '../../../static/images/travel/personal/pic05.png',
		text: '联系客服',
		url: '/pages/customer-platform/my/customerService'
	},
	{
		icon: '../../../static/images/travel/personal/pic04.png',
		text: '公司介绍',
		url: '/pages/customer-platform/my/customerAbout'
	},
	{
		icon: '../../../static/images/travel/personal/pic06.png',
		text: '开具发票',
		url: '/pages/customer-platform/my/fapiao'
	}
]);

const userInfo = ref({
	name: '',
	gender: '',
	age: '',
	birthday: '',
	phoneNumber: '',
	name: '',
	id: ''
});

const isLoggedIn = ref(uni.getStorageSync('isLoggedIn') || false);
const showAuthModal = ref(false);
const todayAppointments = ref([]);

// 添加 wxLoginHandler 方法
const wxLoginHandler = async () => {
  console.log('开始获取登录code...');
  try {
    const loginRes = await new Promise((resolve, reject) => {
      wx.login({
        success: (res) => {
          if (res.code) {
            console.log('登录成功，code:', res.code); 
            console.log('code类型:', typeof res.code);
            resolve(res.code);
          } else {
            console.error('获取code失败');
            reject(new Error('登录失败'));
          }
        },
        fail: (err) => {
          console.error('wx.login调用失败:', err);
          reject(err);
        }
      });
    });

    // 获取 openid
    const openIdRes = await getOpenId(loginRes);
    console.log('获取openid成功:', openIdRes);
    
    // 存储 openid
    if(openIdRes.code === 200) {
      uni.setStorageSync('openid', openIdRes.data.openid);
    }

    return loginRes;
  } catch(err) {
    console.error('登录过程失败:', err);
    throw err;
  }
};

// 修改 handleGetPhoneNumber 方法
const handleGetPhoneNumber = async (e) => {
  if (e.detail.errMsg !== 'getPhoneNumber:ok') {
    console.error('获取手机号失败:', e.detail.errMsg);
    uni.showToast({
      title: '获取手机号失败', 
      icon: 'none'
    });
    return;
  }

  try {
    console.log('开始获取登录code...');
    const loginCode = await wxLoginHandler();
    console.log('获取到登录code:', loginCode);
    
    console.log('开始获取手机号...');
    console.log('手机号code:', e.detail.code);
    
    // 调用登录接口
    const res = await wxLogin({
      code: e.detail.code,
      loginCode: loginCode
    });
    console.log('登录接口返回:', res);

    if (res.code === 200) {
      // 保存用户信息
      uni.setStorageSync('isLoggedIn', true);
      uni.setStorageSync('userId', res.data.userId);
      uni.setStorageSync('phoneNumber', res.data.phoneNumber);
      uni.setStorageSync('userInfo', JSON.stringify({
        name: res.data.name,
        gender: res.data.gender,
        age: res.data.age,
        birthday: res.data.birthday,
        phoneNumber: res.data.phoneNumber
      }));

      // 更新 userInfo 数据
      userInfo.value = {
        name: res.data.name,
        gender: res.data.gender,
        age: res.data.age,
        birthday: res.data.birthday,
        phoneNumber: res.data.phoneNumber
      };

      isLoggedIn.value = true;
      showAuthModal.value = false;
      
      await nextTick();
      uni.showToast({
        title: '登录成功',
        icon: 'success'
      });
    } else {
      throw new Error(res.msg || '获取手机号失败');
    }
  } catch (err) {
    console.error('登录失败:', err);
    uni.showToast({
      title: err.message || '登录失败',
      icon: 'none' 
    });
  }
};

const handleLoginClick = async () => {
	console.log('立即登录按钮被点击');
	showAuthModal.value = true;
	await nextTick(); // 确保视图更新
	console.log('showAuthModal:', showAuthModal.value);
};

const onChooseAvatar = (e) => {
	const { avatarUrl } = e.detail;
	userInfo.value.headImg = avatarUrl;
	uni.setStorageSync('userInfo', JSON.stringify(userInfo.value));
};

onMounted(() => {
	// 从本地存储中获取用户信息
	const storedUserInfo = uni.getStorageSync('userInfo');
	if (storedUserInfo) {
		userInfo.value = JSON.parse(storedUserInfo);
	}
	// 从本地存储中获取今日预约
	const storedTodayAppointments = uni.getStorageSync('todayAppointments');
	if (storedTodayAppointments) {
		todayAppointments.value = JSON.parse(storedTodayAppointments);
	}
});

// 处理功能项点击
const downloadFile = async (url) => {
	try {
		console.log('开始下载文件:', url);
		const res = await new Promise((resolve, reject) => {
			wx.downloadFile({
				url: url,
				success: function (res) {
					if (res.statusCode === 200) {
						console.log('文件下载成功，临时路径:', res.tempFilePath);
						resolve(res.tempFilePath);
					} else {
						console.error('文件下载失败，状态码:', res.statusCode);
						reject(new Error('下载文件失败'));
					}
				},
				fail: function (err) {
					console.error('文件下载失败:', err);
					reject(err);
				}
			});
		});
		return res;
	} catch (err) {
		console.error('文件下载失败:', err);
		return null;
	}
};

const handleFunctionClick = async (item) => {
	if (!isLoggedIn.value) {
		uni.showToast({
			title: '请先登录',
			icon: 'none'
		});
		return;
	}
	// 	if (item.text === '修改个人资料') {
	//     uni.showToast({
	//       title: '该功能待开发',
	//       icon: 'none'
	//     });
	//     return;
	//   }

	if (item.text === '我的所有预约') {
		await fetchAllAppointments();
		uni.navigateTo({
			url: '/pages/customer-platform/my/history'
		});
	} else if (item.text === '公司介绍') {
		console.log('开始下载文件...');
		uni.showLoading({
			title: '正在下载文件...',
			mask: true
		});
		try {
			const filePath = await downloadFile('https://cloud-minapp-47896.cloud.ifanrusercontent.com/1u7WveKJ7yV1KFlG.pdf');
			uni.hideLoading();
			if (filePath) {
				console.log('文件下载成功，路径:', filePath);
				wx.openDocument({
					filePath: filePath,
					fileType: 'pdf',
					success: function (res) {
						console.log('打开文档成功');
					},
					fail: function (err) {
						console.error('打开文档失败:', err);
						uni.showToast({
							title: '打开文档失败',
							icon: 'none'
						});
					}
				});
			} else {
				console.error('文件下载失败');
				uni.showToast({
					title: '文件下载失败',
					icon: 'none'
				});
			}
		} catch (err) {
			uni.hideLoading();
			console.error('文件下载失败:', err);
			uni.showToast({
				title: '文件下载失败',
				icon: 'none'
			});
		}
	} else {
		navigateToPage(item.url);
	}
};

// 获取所有预约
const fetchAllAppointments = async () => {
	try {
		const phoneNumber = uni.getStorageSync('phoneNumber');
		if (!phoneNumber) return;
		console.log("phoneNumber", phoneNumber);
		const res = await getCustomerOrderList({ patientContact: phoneNumber });
		console.log("res", res);
		if (res.code === 200) {
			const allAppointments = processAppointments(res.data.list);
			console.log("allAppointments", allAppointments);
			// 过滤今日预约
			const today = new Date().toISOString().split('T')[0]; // 获取当前日期
			const todayAppointments = allAppointments.filter(appointment => {
				return appointment.appointmentStartDate <= today && appointment.appointmentEndDate >= today;
			});
			uni.setStorageSync('allAppointments', JSON.stringify(allAppointments));
			uni.setStorageSync('todayAppointments', JSON.stringify(todayAppointments));
			console.log("allAppointments", allAppointments);
			console.log("todayAppointments", todayAppointments);
		}
	} catch (err) {
		console.error('获取预约记录失败:', err);
	}
};

// 处理预约数据
const processAppointments = (orderList) => {
	const appointments = [];

	orderList.forEach(order => {
		appointments.push({
			serviceName: order.serviceName,
			appointmentStartDate: order.appointmentStartDate,
			appointmentEndDate: order.appointmentEndDate,
			startTime: order.serviceStartTime,
			endTime: order.serviceEndTime,
			status: order.status
		});
	});

	return appointments;
};
</script>

<style lang="scss" scoped>
/* 样式可以根据实际情况调整 */
.homepage {
	width: 100%;
	height: auto;
	padding-top: 180rpx;
	background: linear-gradient(1deg, rgba(247, 240, 255, 0.1900) 0%, rgba(229, 232, 255, 0.2000) 68%, rgba(231, 228, 255, 0.6600) 100%);

	& text {
		color: #333333;
		font-family: PingFangSC-Semibold, PingFang SC;
	}

	.people {
		padding: 0 42rpx 28rpx 32rpx;
		display: flex;
		align-items: center;

		.headImg {
			width: 100rpx;
			height: 100rpx;
			border-radius: 50rpx;
			overflow: hidden;
			display: flex;
			justify-content: center;
			align-items: center;

			.avatar-button {
				background: none;
				border: none;
				padding: 0;
				margin: 0;
				width: 100%;
				height: 100%;
				display: flex;
				justify-content: center;
				align-items: center;

				.avatar {
					width: 100%;
					height: 100%;
					border-radius: 50%;
				}
			}
		}

		.info {
			flex: 1;
			margin-top: 20rpx;

			.nick {
				display: flex;

				>text {
					font-size: 36rpx;
					font-weight: 600;
					line-height: 50rpx;
				}
			}

			.grade {
				display: flex;
				align-items: center;

				>view {
					display: flex;
					align-items: center;
					margin-right: 12rpx;

					& text {
						font-size: 20rpx;
						font-weight: 600;
						color: #FFFFFF;
						line-height: 28rpx;
						text-shadow: 0rpx 2rpx 4rpx rgba(0, 0, 0, 0.5000);
					}

					& image {
						width: 28rpx;
						height: 30rpx;
					}

					&:last-child {
						>image {
							width: 40rpx;
							height: 40rpx;
						}

						>text {
							margin-left: -6rpx;
						}
					}
				}
			}

			.userId {
				width: fit-content;
				display: flex;
				background: #F5F5FF;
				border-radius: 8rpx;
				margin: 20rpx 0;
				box-shadow: 0rpx 2rpx 6rpx 1rpx rgba(0, 0, 0, 0.1400), 0rpx -4rpx 6rpx 0rpx #FFFFFF;

				>image {
					width: 36rpx;
					height: 40rpx;
				}

				.number {
					justify-content: center;

					>text {
						font-size: 24rpx;
						font-weight: 600;
						line-height: 40rpx;

						&:last-child {
							font-weight: 500;
							font-size: 22rpx;
							margin-left: 8rpx;
						}
					}
				}
			}
		}
	}

	.list {
		width: 100%;
		display: flex;
		padding: 0 44rpx;
		box-sizing: border-box;

		.item {
			width: 25%;
			display: flex;
			justify-content: space-evenly;
			align-items: center;

			.text {
				display: flex;
				flex-direction: column;
				align-items: center;

				>text:first-child {
					font-size: 36rpx;
					font-family: CloudHeiChaoGBK;
					line-height: 48rpx;
					font-weight: 600;
				}

				>text:last-child {
					font-size: 24rpx;
					color: #999999;
					line-height: 34rpx;
				}
			}
		}
	}

	.infos {
		padding: 0 40rpx;


		.tool {
			width: 100%;
			height: auto;
			background: #FFFFFF;
			box-shadow: 0rpx 2rpx 22rpx 0rpx rgba(114, 118, 206, 0.2700);
			border-radius: 28rpx;
			margin: 22rpx 0;
			padding: 15rpx 0;

			.orderTitle {
				color: #ebbd60;
				font-size: 30rpx;
				letter-spacing: 7rpx;
				font-weight: bolder;
				padding: 20rpx;
			}

			.no-appointment-tip {
				text-align: center;
				margin-top: 20rpx;
				color: #999999;
				font-size: 28rpx;
			}

			.nav-item {
				height: fit-content;
				padding: 20rpx 10px;
				border-radius: 8px;
				margin: 17rpx;
				border: 1rpx solid rgba($color: #989797, $alpha: .3);

				.thing {
					font-size: 32rpx;
					float: right;
				}

				.time {
					font-size: 32rpx;
				}
			}
		}

		.order-buttons {
			display: flex;
			justify-content: space-around;
			margin-top: 20rpx;
			padding: 20rpx;
			background-color: #fff;
			border-radius: 20rpx;
			box-shadow: 0rpx 4rpx 10rpx rgba(0, 0, 0, 0.1);
		}

		.order-button {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			width: 150rpx;
			height: 150rpx;
			background-color: #fff;
			border: 1rpx solid #eee;
			border-radius: 20rpx;
			font-size: 24rpx;
			color: #333;
			text-align: center;
			box-shadow: 0rpx 2rpx 4rpx rgba(0, 0, 0, 0.1);
			transition: transform 0.2s ease;
			padding: 12rpx;
			box-sizing: border-box;
			gap: 8rpx;

			&:active {
				transform: scale(0.95);
			}
		}

		.button-icon {
			width: 50rpx;
			height: 50rpx;
			flex-shrink: 0;
		}

		.set {
			width: 100%;
			padding: 34rpx 24rpx 44rpx 34rpx;
			background: #FFFFFF;
			box-shadow: 0rpx 2rpx 28rpx 0rpx rgba(142, 146, 230, 0.2700);
			border-radius: 28rpx;
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			box-sizing: border-box;

			>view {
				display: flex;
				align-items: center;
				margin-bottom: 35rpx;

				& text {
					flex: 1;
					font-size: 28rpx;
					line-height: 40rpx;
					margin-left: 30rpx;
					font-size: 24rpx;
					line-height: 1.2;
					white-space: nowrap;
					max-width: 100%;
					overflow: hidden;
					text-overflow: ellipsis;
				}

				.icon {
					width: 36rpx;
					height: 36rpx;
				}

				.right {
					width: 40rpx;
					height: 40rpx;
				}
			}
		}

		.service {
			background: #FFFFFF;
			box-shadow: 0rpx 2rpx 28rpx 0rpx rgba(142, 146, 230, 0.2700);
			border-radius: 28rpx;
			margin-top: 26rpx;
			padding: 34rpx 24rpx 44rpx 34rpx;
			display: flex;
			flex-direction: column;
			justify-content: space-between;

			>view {
				display: flex;
				align-items: center;

				& text {
					flex: 1;
					font-size: 28rpx;
					line-height: 40rpx;
					margin-left: 30rpx;
				}

				.icon {
					width: 36rpx;
					height: 36rpx;
				}

				.right {
					width: 40rpx;
					height: 40rpx;
				}
			}
		}
	}

	.change {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		justify-content: space-between;
		padding: 20rpx;
		background-color: #fff;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
		z-index: 1000;

		.change_user,
		.change_nurse {
			flex: 1;
			margin: 0 10rpx;
			font-size: 32rpx;
			border-radius: 15rpx;
			background-color: #919191;
			color: #333333;
		}

		.change_nurse {
			background-color: #ffcc00;
		}
	}
}

.login-button {
	margin-left: auto;
	padding: 10rpx 20rpx;
	background-color: #ffcc00;
	border-radius: 8rpx;
	color: #333333;
	font-size: 28rpx;
	cursor: pointer;
}

.auth-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	justify-content: center;
	align-items: center;
	z-index: 1000;

	.auth-modal-content {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 32rpx;
		width: 80%;
		max-width: 600rpx;

		.auth-modal-header {
			font-size: 32rpx;
			font-weight: bold;
			margin-bottom: 16rpx;
		}

		.auth-modal-body {
			font-size: 28rpx;
			margin-bottom: 32rpx;
		}

		.auth-modal-footer {
			display: flex;
			justify-content: space-between;

			.auth-modal-button {
				padding: 10rpx 20rpx;
				border-radius: 8rpx;
				font-size: 28rpx;
				cursor: pointer;

				&-cancel {
					background-color: #f0f0f0;
					color: #333333;
				}

				&-confirm {
					background-color: #ffcc00;
					color: #333333;
				}
			}
		}
	}
}
</style>